from distutils.util import strtobool
from typing import Dict, Union

from sqlalchemy.orm import Session

from core.security import security
from app.auth.models import AuthUsers
from app.auth.handlers.auth_ldap_handler import AuthLdapHandler
from app.login.schemas import VerityUserIn
from common.redispy import redispy

from core.logger import logger

__all__ = ["verity_user"]


def verity_user(db: Session, username: str, password: str) -> Dict:
    # 判断用户是否允许登录
    if not redispy.is_login_allow(username):
        logger.error(f"user:{username} too many login failures, rest for 30 minutes")
        return None
    
    auth_ldap_handler = AuthLdapHandler()
    user = AuthUsers.get_by_username(db, username)
    if not user:
        user = auth_ldap_handler.get_user(uid=username)
        if user: 
            AuthUsers.add(db, {'username': user.get('username'), 'nick_name': user.get('username'), 'auth_type': 'ldap',
                               'email': user.get('mail'), 'mobile': user.get('mobile'),
                               'hash_password': security.create_password_hash(password), 'is_superuser': False, 'is_active': True})
        else:
            return {}
        
    # 用户是否激活
    user = VerityUserIn(**user)
    if not strtobool(user.is_active):
        return {}
    
    if user.auth_type == 'ldap':
        # ldap认证
        result = auth_ldap_handler.bind_user(uid=username, password=password)
        if not result:
            logger.error(f"user:{username} ldap login failed")
            redispy.set_login_failed(user.username)
            return {}
    elif user.auth_type == 'mysql':
        # mysql认证
        result = security.verify_password(password, user.hash_password)
        if not result:
            logger.error(f"user:{username} mysql login failed")
            redispy.set_login_failed(user.username)
            return {}
    else:
        logger.error(f"user:{username} auth_type invalid")
        redispy.set_login_failed(user.username)
        return {}
    
    result = {"uuid": user.uuid, "username": user.username, "avatar": user.avatar, "is_active": user.is_active,
            "is_superuser": user.is_superuser}
    redispy.set_login_success(user.username)
    return result
    



